package com.ferry.transport.netty.handler.server;
import	java.util.concurrent.atomic.AtomicInteger;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

@ChannelHandler.Sharable
public class AcceptorIdleStateTrigger extends ChannelInboundHandlerAdapter {

    private AtomicInteger lossCount = new AtomicInteger(0);

    private static final int MAX_LOSS_COUNT = 5;

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleState state = ((IdleStateEvent) evt).state();
            if (state == IdleState.READER_IDLE) {
                //throw new RuntimeException("idle exception");
                int i = lossCount.incrementAndGet();
                if (i >= MAX_LOSS_COUNT) {
                    ctx.channel().close(); //关闭通道
                }
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }
}